<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller;

use think\facade\Db;
use app\BaseController;
use app\wework\model\BaseModel;
use app\wework\model\user\staff\StaffModel;
use think\facade\Log;
use app\wework\model\QyWechatApi;
include "../extend/Qywxcypto/WXBizMsgCrypt.php";

/**
* 通讯录回调
**/
class SatffCallback extends BaseController
{
	public $wid;
	public $config = [];
	/**
     * 通讯录回调入口
     * 
     * @return \think\Response
     */
	public function index(){
		if(isset($_GET['echostr'])){
			  //接受验证数据
		  	  $sVerifyMsgSig = $_GET['msg_signature'];
			  $sVerifyTimeStamp = $_GET['timestamp'];
			  $sVerifyNonce = $_GET['nonce'];
			  $sVerifyEchoStr = $_GET['echostr'];
			  $configList = BaseModel::getAll('kt_wework_config');
			  foreach($configList as $config){
				  $encodingAesKey = $config['user_aes'];
				  $token = $config['user_tokent'];
				  $corpId = $config['corp_id'];
				  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
				  // 需要返回的明文
				  $sEchoStr = "";
				  $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
				  if($errCode == 0){
					   echo $sEchoStr;
					   exit();
				  }
			  } 
		}else{
			//搜集参数
			$sReqMsgSig = $_GET['msg_signature'];
			$sReqTimeStamp = $_GET['timestamp'];
			$sReqNonce = $_GET['nonce'];
			//获取xml冰去除特殊字符
			$sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
			//解密
			$this->config = $config = BaseModel::find('kt_wework_config',['corp_id'=>xmlToArray($sReqData)['ToUserName']]);
			if(!$config) {
				Log::info("通讯录回调: 未找到企业");
				echo "success";
				exit();
			}
			$encodingAesKey = $config['user_aes'];
			$token = $config['user_tokent'];
			$corpId = $config['corp_id'];
			$wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			$sMsg = "";  // 解析之后的明文
			$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
			if ($errCode == 0) {
			  // 解密成功，sMsg即为xml格式的明文
			  // TODO: 对明文的处理
			  /*
			  "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
			  <FromUserName><![CDATA[mycreate]]></FromUserName>
			  <CreateTime>1409659813</CreateTime>
			  <MsgType><![CDATA[text]]></MsgType>
			  <Content><![CDATA[hello]]></Content>
			  <MsgId>4561255354251345929</MsgId>
			  <AgentID>218</AgentID>
			  </xml>"
			  */

			  $arr = xmlToArray($sMsg);
			  Log::error(json_encode($arr,320));
			  switch ($arr['ChangeType']) {
			  	case 'create_user':
			  		$this->createStaff($arr);
			  		break;
			  	case 'update_user':
			  		$this->updateStaff($arr);
			  		break;
			  	case 'delete_user':
			  		$this->deleteStaff($arr);
			  		break;
			  	case 'create_party':
			  		$this->createParty($arr);
			  		break;
			  	case 'update_party':
			  		$this->updateParty($arr);
			  		break;
			  	case 'delete_party':
			  		$this->deleteParty($arr);
			  		break;
			  	default:
			  		# code...
			  		break;
			  }
			} else {
			  Log::info("解密失败ERR: " . $errCode . "\n\n");
			}
			echo "success";
			exit();
		}
	}

	/**
	* 新增成员
	* @param $arr 回调数据
	*
	**/
	public function createStaff($arr){
		$corpID = $arr['ToUserName'];//企业微信CorpID
		$config = $this->config;
		//获取部门列表
		$departmentRes = QyWechatApi::getDepartmentList($config["wid"]);
		$departmentList = $departmentRes['department'];
		$departmentArr = array_column($departmentList,'name','id');

		$department_name = [];
		  foreach($arr['Department'] as $departmentId){
		  $department_name[] = $departmentArr[$departmentId];
		}
		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		$qyUser->wid = $qyConfig->wid;
		$qyUser->userid = $arr['UserID'];
		$qyUser->name = Helper::getInstance()->filterEmoji($arr['Name']);
		$qyUser->mobile = $arr['Mobile'];
		$qyUser->department = json_encode($arr['Department']);
		$qyUser->department_name = json_encode($department_name,320);
		$qyUser->position = $arr['Position'];
		$qyUser->gender = $arr['Gender'];
		$qyUser->email = $arr['Email'];
		$qyUser->is_leader_in_dept = json_encode($arr['IsLeaderInDept']);
		$qyUser->avatar = $arr['Avatar'];
		$qyUser->telephone = $arr['Telephone'];
		$qyUser->alias = $arr['Alias'];
		$qyUser->extattr = json_encode($arr['ExtAttr']);
		$qyUser->status = $arr['Status'];
		$qyUser->address = $arr['Address'];
		$qyUser->is_del = 0;
		$qyUser->save();
	}

	/**
	* 更新成员
	* @param $arr 回调数据
	*
	**/
	public function updateStaff($arr){
		$corpID = $arr['ToUserName'];//企业微信CorpID
		$config = $this->config;
		//获取部门列表
		$departmentRes = QyWechatApi::getDepartmentList($config["wid"]);
		$departmentList = $departmentRes['department'];
		$departmentArr = array_column($departmentList,'name','id');

		$department_name = [];
		  foreach($arr['Department'] as $departmentId){
		  $department_name[] = $departmentArr[$departmentId];
		}
		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		$qyUser->wid = $qyConfig->wid;
		$qyUser->userid = $arr['UserID'];
		$qyUser->name = Helper::getInstance()->filterEmoji($arr['Name']);
		$qyUser->mobile = $arr['Mobile'];
		$qyUser->department = json_encode($arr['Department']);
		$qyUser->department_name = json_encode($department_name,320);
		$qyUser->position = $arr['Position'];
		$qyUser->gender = $arr['Gender'];
		$qyUser->email = $arr['Email'];
		$qyUser->is_leader_in_dept = json_encode($arr['IsLeaderInDept']);
		$qyUser->avatar = $arr['Avatar'];
		$qyUser->telephone = $arr['Telephone'];
		$qyUser->alias = $arr['Alias'];
		$qyUser->extattr = json_encode($arr['ExtAttr']);
		$qyUser->status = $arr['Status'];
		$qyUser->address = $arr['Address'];
		$qyUser->is_del = 0;
		$qyUser->save();
	}

	 //删除成员
	  public function deleteStaff($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyUser->is_del = 1;
		  $qyUser->save();
	  }



	 /**
	 * 新增部门事件
	 **/
	 public function createParty($arr){
	 	$CorpID = $arr['ToUserName'];//企业微信CorpID
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		$department = new Model('qy_department_list');
		$department->wid = $qyConfig->wid;
		$department->department_id = $arr['Id'];
		$department->department_name = $arr['Name'];
		$department->department_parentid = $arr['ParentId'];
		$department->department_order = $arr['Order'];
		$department->ctime = $arr['CreateTime'];
		$department->save();
	 }
	 /**
	 * 更新部门事件
	 **/
	 public function updateParty($arr){
	 	$CorpID = $arr['ToUserName'];//企业微信CorpID
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		$department = (new Model('qy_department_list'))->find(['wid'=>$qyConfig->wid,'department_id'=>$arr['Id']]);
		if(!$department->id){
			return '';
		}
		$department->department_name = $arr['Name'];
		$department->department_parentid = $arr['ParentId'];
		$department->ctime = $arr['CreateTime'];
		$department->save();
	 }
	 /**
	 * 删除部门事件
	 **/
	 public function deleteParty($arr){
	 	$CorpID = $arr['ToUserName'];//企业微信CorpID
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		$department = (new Model('qy_department_list'))->find(['wid'=>$qyConfig->wid,'department_id'=>$arr['Id']]);
		if(!$department->id){
			return '';
		}
		$department->remove();
	 }
}